//
// ***********************************************
// *    ___________   ___________  __      __    *
// *   |______  __/  /_____  ___/  \ \    / /    *
// *         / /          / /       \ \  / /     *
// *        / /          / /         \ \/ /      *
// *       / /          / /           \  /       *
// *      / /______    / /            / /        *
// *     /________/   /_/            /_/         *
// *                                             *
// ***********************************************
//
//   ZTYTools.m
//   VolumerSDK
//   
//   Created  by mac on 2019/6/28
//   Modified by Tiyon
//   Copyright © 2019 wanmeizty. All rights reserved.
//   
   

#import "ZTYTools.h"
#import <SystemConfiguration/CaptiveNetwork.h>
//#import <NetworkExtension/NetworkExtension.h>
//#import <sys/utsname.h>


#import <UIKit/UIKit.h>

#import <CommonCrypto/CommonCrypto.h>

//**toast**//
#define kMD_ScreenSize [UIScreen mainScreen].bounds.size
#define kMD_ScreenWidth kMD_ScreenSize.width
#define kMD_ScreenHeight kMD_ScreenSize.height

@interface ZTYTools ()

//**toast**//
@property (nonatomic,strong) UIWindow *window;
@property (nonatomic,strong) UILabel *messageLabel;


@end

@implementation ZTYTools

// 获取设备ID
+(NSString*)getDeviceId{
    NSString *bundleId = [[NSBundle mainBundle] bundleIdentifier];
    NSString * UDID = (NSString *)[ZTYTools loadInKey:bundleId];
//    [ZTYTools deleteKeyData:bundleId];
    if (UDID== nil || UDID.length <= 0) {
        //生成一个uuid的方法
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        UDID = (NSString *)CFBridgingRelease(CFUUIDCreateString (kCFAllocatorDefault,uuidRef));
//        UDID = [UDID stringByReplacingOccurrencesOfString:@"-" withString:@""];
        [ZTYTools saveInkeyChain:bundleId data:UDID];
    }
    return UDID;
}


+(NSString *)getPhoneInfoString{
    
    return [NSString stringWithFormat:@"imei=%@;wifiMac=%@;blueMac=02:00:00:00:00:00;cpuModel=arm64-v8a;brand=iPhone;storageSize=56931368960;",[self getDeviceId],[self wifiMac]];
}

+(NSString *)getDeviceImei{
    return [self getDeviceId];
}

+ (NSString *)wifiMac
{
    NSArray *ifs = CFBridgingRelease(CNCopySupportedInterfaces());
    id info = nil;
    for (NSString *ifname in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((CFStringRef) ifname);
        if (info && [info count]) {
            break;
        }
    }
    NSDictionary *dic = (NSDictionary *)info;
    NSString *bssid = [dic objectForKey:@"BSSID"];
    if (bssid == nil)bssid = @"";
    return bssid;
}

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (id)kSecClassGenericPassword,(id)kSecClass,
            service, (id)kSecAttrService,
            service, (id)kSecAttrAccount,
            (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
            nil];
}

// keychain 保存数据
+ (void)saveInkeyChain:(NSString *)service data:(id)data {
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Delete old item before add new item
    SecItemDelete((CFDictionaryRef)keychainQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
}

// keychain 保存数据
+ (id)loadInKey:(NSString *)service {
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Configure the search setting
    //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        } @finally {
        }
    }
    if (keyData)
        CFRelease(keyData);
    return ret;
}


// keychain 删除数据
+ (void)deleteKeyData:(NSString *)service {
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}

static ZTYTools *calendar;
+ (instancetype)sharedTools{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        calendar = [[ZTYTools alloc] init];
    });

    return calendar;
}

+(NSString *)md5:(nullable NSString *)str{
    if (!str) return nil;
    
    const char *cStr = str.UTF8String;
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    NSMutableString *md5Str = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
        [md5Str appendFormat:@"%02x", result[i]];
    }
    return md5Str;
}

+(void)askNetWork:(NSString *)url param:(NSDictionary * )params postMethed:(BOOL)isPost hasCookie:(BOOL)hasCookie finishBlock:(void(^)(NSData * data,NSError * error))finishBlock{
    
    // 1.创建一个网络路径
    // 2.创建一个网络请求
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    if (hasCookie) {
        NSArray * cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
        NSDictionary * cookieDic = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
        [request setValue:[cookieDic objectForKey:@"Cookie"] forHTTPHeaderField:@"Cookie"];
    }
    if (isPost) {
//        NSString * body = [self parameters:params];
//        //设置请求参数
//        request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
        request.HTTPMethod = @"POST";
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
        [request setHTTPBody:jsonData];
    }else{
        request.HTTPMethod = @"GET";
    }
    // 3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    // 4.根据会话对象，创建一个Task任务：
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        /*           对从服务器获取到的数据data进行相应的处理：         */
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@",dic);
        finishBlock(data,error);
        
    }];
    // 5.最后一步，执行任务（resume也是继续执行）:
    [sessionDataTask resume];
}

+(NSDictionary *)convertDicFromString:(NSString *)url;{
    //获取问号的位置，问号后是参数列表
    NSRange range = [url rangeOfString:@"?"];
    //获取参数列表
    NSString *propertys = [url substringFromIndex:(int)(range.location+1)];
    
    //进行字符串的拆分，通过&来拆分，把每个参数分开
    NSArray *subArray = [propertys componentsSeparatedByString:@"&"];
    
    //把subArray转换为字典
    //tempDic中存放一个URL中转换的键值对
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithCapacity:4];
    
    for (int j = 0 ; j < subArray.count; j++)
    {
        //在通过=拆分键和值
        NSArray *dicArray = [subArray[j] componentsSeparatedByString:@"="];
        if (dicArray.count > 1) {
            //给字典加入元素
            [tempDic setObject:dicArray[1] forKey:dicArray[0]];
        }
    }
    return tempDic;
}

/**
 拼接字典数据
 
 @param parameters 参数
 @return 拼接后的字符串
 */
+(NSString *)parameters:(NSDictionary *)parameters
{
    //创建可变字符串来承载拼接后的参数
    NSMutableString *parameterString = [NSMutableString new];
    //获取parameters中所有的key
    NSArray *parameterArray = parameters.allKeys;
    for (int i = 0;i < parameterArray.count;i++) {
        //根据key取出所有的value
        id value = parameters[parameterArray[i]];
        //把parameters的key 和 value进行拼接
        NSString *keyValue = [NSString stringWithFormat:@"%@=%@",parameterArray[i],value];
        if (i == parameterArray.count || i == 0) {
            //如果当前参数是最后或者第一个参数就直接拼接到字符串后面，因为第一个参数和最后一个参数不需要加 “&”符号来标识拼接的参数
            [parameterString appendString:keyValue];
        }else
        {
            //拼接参数， &表示与前面的参数拼接
            [parameterString appendString:[NSString stringWithFormat:@"&%@",keyValue]];
        }
    }
    return parameterString;
}


/**Toast**/
- (UIWindow *)window{
    if(_window == nil){
        NSArray  *windows = [UIApplication sharedApplication].windows;
        _window = [[UIWindow alloc] init];
        _window.hidden = NO;
        _window.windowLevel = [(UIWindow *)windows.lastObject windowLevel] + 1;
        _window.userInteractionEnabled = NO;
        _window.alpha = 0.6;
        _window.backgroundColor = [UIColor clearColor];
    }
    return _window;
}

+ (void)showMessage:(NSString *)message{
    [self showMessage:message showTime:1.2f finished:nil];
}
+ (void)showMessage:(NSString *)message showTime:(NSTimeInterval)duration{
    [[self sharedTools] showMessage:message showTime:duration finished:nil];
}

+ (void)showMessage:(NSString *)message
           showTime:(NSTimeInterval)duration
           finished:(void(^)(void))finished {
    [[self sharedTools] showMessage:message showTime:duration finished:finished];
}

+ (void)showMessage:(NSString *)message
           showTime:(NSTimeInterval)duration
           finished:(void(^)(void))finished withDirection:(BOOL)isLeftRight{
    
    [[self sharedTools] showMessage:message showTime:duration finished:finished withDirection:isLeftRight];
    
}

- (void)showMessage:(NSString *)message showTime:(NSTimeInterval)duration finished:(void(^)(void))finished withDirection:(BOOL)isLeftRight{
    if (message.length == 0) return;
    
    if (isLeftRight) {
        [self.window setTransform:CGAffineTransformMakeRotation(M_PI/2)];
    }
    UILabel *label = [[UILabel alloc] init];
    _messageLabel = label;
    label.backgroundColor = [UIColor blackColor];
    label.textColor = [UIColor whiteColor];
    label.text = message;
    label.preferredMaxLayoutWidth = kMD_ScreenWidth - 60.0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.textAlignment = NSTextAlignmentCenter;
    label.numberOfLines = 0;
    label.layer.cornerRadius = 4;
    label.layer.masksToBounds = YES;
    label.font = [UIFont systemFontOfSize:13];
    
    CGRect rect = [message boundingRectWithSize:CGSizeMake(kMD_ScreenWidth - 60, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil];
    label.frame = CGRectMake(0, 0, rect.size.width+10, rect.size.height + 10);
    label.center = CGPointMake(kMD_ScreenWidth/2.0, kMD_ScreenHeight*0.5);
    [self.window addSubview:label];
    label.alpha = 0;
    
    [UIView animateWithDuration:0.2 animations:^{
        label.alpha = 1;
    } completion:^(BOOL finish) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [label removeFromSuperview];
            self.window.hidden = YES;
            self.window = nil;
            if (finished) {
                finished();
            }
        });
    }];
}

- (void)showMessage:(NSString *)message showTime:(NSTimeInterval)duration finished:(void(^)(void))finished {
    if (message.length == 0) return;
    __weak __typeof(self) weakSelf = self;
    UILabel *oldlabel = [self.window viewWithTag:333];
    if (oldlabel) [oldlabel removeFromSuperview];
    
    UILabel *label = [[UILabel alloc] init];
    _messageLabel = label;
    label.backgroundColor = [UIColor blackColor];
    label.textColor = [UIColor whiteColor];
    label.text = message;
    label.preferredMaxLayoutWidth = kMD_ScreenWidth - 60.0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.textAlignment = NSTextAlignmentCenter;
    label.numberOfLines = 0;
    label.layer.cornerRadius = 4;
    label.tag = 333;
    label.layer.masksToBounds = YES;
    label.font = [UIFont systemFontOfSize:13];
    
    CGRect rect = [message boundingRectWithSize:CGSizeMake(kMD_ScreenWidth - 60, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil];
    label.frame = CGRectMake(0, 0, rect.size.width+10, rect.size.height + 10);
    label.center = CGPointMake(kMD_ScreenWidth/2.0, kMD_ScreenHeight*0.55);
    [self.window addSubview:label];
    label.alpha = 0;
    
    [UIView animateWithDuration:0.2 animations:^{
        label.alpha = 1;
    } completion:^(BOOL finish) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [label removeFromSuperview];
            strongSelf.window.hidden = YES;
            strongSelf.window = nil;
            if (finished) {
                finished();
            }
        });
    }];
}

@end
